package persistence

import (
	"context"

	"github.com/samber/do/v2"
	"gorm.io/gorm"

	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/domain/entity"
	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/domain/repository"
	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/infrastructure/persistence/model"
)

type ProductPersistence struct {
	db *gorm.DB
}

func NewProductRepository(i do.Injector) (repository.ProductRepository, error) {
	db := do.MustInvoke[*gorm.DB](i)
	return &ProductPersistence{
		db: db,
	}, nil
}

func (p *ProductPersistence) Save(ctx context.Context, tx *gorm.DB, product *entity.Product) error {

	productModel := &model.Product{
		ID:          product.ID,
		GoodsSn:     product.GoodsSN,
		MerchantID:  0, // 这里 merchantID 先写 0
		Name:        product.Name,
		CategoryID:  product.CategoryID,
		Description: product.Description,
		MainImage:   "", // 主图也先置空
		Status:      0,  // status 也先置为0
	}

	tx = tx.WithContext(ctx).Create(&productModel)
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}
